﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace OFDParserLibrary
{
    /// <summary>
    /// winrar.exe工具类
    /// </summary>
    internal static class WinRarHelper
    {
        /// <summary>
        /// 判断终端电脑是否安装WinRar程序，并返回安装路径
        /// </summary>
        /// <returns></returns>
        public static string IsExistWinRar()
        {
            string result = "";
            string key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe";
            using(RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(key))
            {
                if (registryKey != null)
                {
                    result = registryKey.GetValue("").ToString();
                }
            }
            return result;
        }
        /// <summary>
        /// 调用winrar.exe进程解压ofd板式发票文件
        /// </summary>
        /// <param name="rarPathName">ofd版式发票文件路径（包含文件名称和后缀）</param>
        /// <returns></returns>
        public static int UnZipFile(string rarPathName, string UnPath)
        {
            if (!Directory.Exists(UnPath))
                Directory.CreateDirectory(UnPath);
            Process process = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "Winrar.exe";
            startInfo.CreateNoWindow = true;
            //x  -ibck  -o+ {0} {1} -y
            string tmpPath = "\"" + rarPathName + "\"";
            string tmpPath2 = "\"" + UnPath + "\"";
            string cmd = string.Format(" x  -ibck -o+ {0} {1} -y", tmpPath, tmpPath2); //覆盖命令( x -o+ 代表覆盖已存在的文件)
            startInfo.Arguments = cmd;
            process.StartInfo = startInfo;
            int ExitCode = 0;  //ExitCode==0正常执行；ExitCode≠0 不正常，详细错误码参见winrar.txt文件说明
            try
            {
                process.Start();
                process.WaitForExit();
                ExitCode = process.ExitCode;
                return ExitCode;
            }
            catch (Exception ex)
            {
                throw new Exception("解压过程抛出异常:"+ex.Message);
            }
            finally
            {
                process.Close();
            }
        }
    }
}
